<template>
  <div id="container">
    <div   id="main">
    <div id="topbtns">
      <el-button
        :loading="downloadLoading" 
        type="primary" 
        style="width:33%;margin:0"
        icon="el-icon-document"
        @click="handleDownload"
      >
        导出Excel
      </el-button>

      
      <el-button
        :loading="downloadLoading" 
        type="primary"
        style="width:33%"
        icon="el-icon-user"
        @click="dialogFormVisible = true"
      >
        新建合同
      </el-button>
      
      <el-button
        :loading="downloadLoading" 
         id="delete"
        type="danger"
        @click="deleteDoc()"
        icon="el-icon-delete"
      >
        离职
      </el-button> 
    </div>
    <el-dialog
      title="新建合同"
      center
      width="60%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="newEmployee"
        label-position="right"
        style="overflow: hidden; margin-top: 30px"
        :rules="rules"
      >
        <el-form-item label="姓名：" prop="name" :label-width="formLabelWidth">
          <el-input
            v-model="newEmployee.name"
            autocomplete="off"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item
          label="性别："
          prop="gender"
          required="true"
          :label-width="formLabelWidth"
        >
          <el-radio v-model="newEmployee.gender" label="1">男</el-radio>
          <el-radio v-model="newEmployee.gender" label="2">女</el-radio>
          <el-radio v-model="newEmployee.gender" label="0">未知</el-radio>
        </el-form-item>
        <el-form-item
          label="学历："
          prop="education"
          :label-width="formLabelWidth"
          required="true"
        >
          <el-select v-model="newEmployee.education" placeholder="请选择学历">
            <el-option label="大专以下" value="大专以下"></el-option>
            <el-option label="大专" value="大专"></el-option>
            <el-option label="本科" value="本科"></el-option>
            <el-option label="研究生" value="研究生"></el-option>
            <el-option label="博士生" value="博士生"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄：" prop="age" :label-width="formLabelWidth">
          <el-input
            v-model.number="newEmployee.age"
            autocomplete="off"
            placeholder="请输入员工年龄"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item
          label="身份证号："
          :label-width="formLabelWidth"
          prop="identityCard"
        >
          <el-input
            v-model="newEmployee.identityCard"
            autocomplete="off"
            placeholder="请输入员工身份证号"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item
          label="部门："
          :label-width="formLabelWidth"
          prop="deptName"
        >
          <el-input
            v-model="newEmployee.deptName"
            id="parentdept"
            style="width: 300px"
            placeholder="请选择部门"
            @focus="openParentDept()"
          ></el-input>
        </el-form-item>
        <el-dialog
          width="30%"
          title="选择部门"
          :visible.sync="innerVisible"
          append-to-body
        >
          <el-tree
            :data="deptList"
            :props="defaultProps"
            @node-click="handleNodeClick"
            accordion
          >
          </el-tree>

          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="selectDept()">确 定</el-button>
            <el-button @click="innerVisible = false">取 消</el-button>
          </span>
        </el-dialog>
        <el-form-item
          label="职位："
          :label-width="formLabelWidth"
          prop="userType"
          required
        >
          <el-radio v-model="newEmployee.userType" label="0">普通员工</el-radio>
          <el-radio v-model="newEmployee.userType" label="3">HR</el-radio>
          <el-radio v-model="newEmployee.userType" label="4">部门经理</el-radio>
        </el-form-item>
        <el-form-item
          label="入职时间："
          prop="entryDate"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="newEmployee.entryDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="手机号："
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="newEmployee.mobile"
            autocomplete="off"
            style="width: 300px"
            placeholder="请输入员工手机号"
          />
        </el-form-item>
        <el-form-item id="image" label="上传员工照片" label-width="200px">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- hr、部门经理用户名密码 -->
      <el-divider
        content-position="left"
        style="position: absolute; left: 500px; top: 300px"
        >HR/部门经理账号设置</el-divider
      >

      <el-form
        :model="newEmployee"
        label-position="right"
        style="overflow: hidden; margin-top: 30px; margin-left: 50px"
        :rules="rules"
        inline="true"
        v-show="isHR"
      >
        <el-form-item label="用户名：" prop="username">
          <el-input
            v-model="newEmployee.username"
            @blur="checkUsername()"
            autocomplete="off"
            placeholder="请输入hr/部门经理登录用户名"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" style="margin-left: 50px">
          <el-input
            v-model="newEmployee.password"
            autocomplete="off"
            placeholder="请输入hr/部门经理登录密码"
            style="width: 300px"
            type="password"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="create">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 员工档案列表 -->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      height="750px"
      id="data"
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      element-loading-text="拼命加载中"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="员工姓名" align="center">
        <template slot-scope="scope">
          <!--          scope.row获取每一行数据-->
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="员工性别" align="center">
        <template slot-scope="scope">
          <!--          scope.row获取每一行数据-->
          <p v-if="scope.row.gender == 1">男</p>
          <p v-if="scope.row.gender == 2">女</p>
          <p v-if="scope.row.gender == 0">未知</p>
        </template>
      </el-table-column>
      <el-table-column label="员工年龄" align="center">
        <template slot-scope="scope">
          {{ scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column label="员工学历" align="center">
        <template slot-scope="scope">
          {{ scope.row.education }}
        </template>
      </el-table-column>
      <el-table-column label="所在部门" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.deptName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="职位" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.userType == 0"
            >普通员工</el-tag
          >
          <el-tag type="warning" v-if="scope.row.userType == 3">hr</el-tag>
          <el-tag type="danger" v-if="scope.row.userType == 4">部门经理</el-tag>
        </template>
      </el-table-column>
       
      <el-table-column align="center" label="入职日期">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.entryDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="medium"
            style="width: 65px"
            plain
            @click="showMsg(scope.row.userId)"
            >编辑</el-button
          >
          <el-button
            type="success"
            style="width: 65px"
            @click="initEvalute(scope.row)"
            plain
            >评价</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="评价" :visible.sync="contentVisitable" width="40%" center>
      <el-form
        label-position="right"
        style="overflow: hidden"
        label-width="150px"
      >
        <el-form-item required="true" label="评价对象：">
          <el-input
            style="width: 300px"
            placeholder="请输入被评价人姓名"
            v-model="contentForm.name"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item required="true" label="工作能力：">
          <el-rate
            v-model="contentForm.workingAbility"
            style="margin-top: 12px"
          ></el-rate>
        </el-form-item>
        <el-form-item label="工作态度：" required="true">
          <el-rate
            v-model="contentForm.workingAttitude"
            style="margin-top: 12px"
          ></el-rate>
        </el-form-item>
        <el-form-item label="协助能力：" required="true">
          <el-rate
            v-model="contentForm.communication"
            style="margin-top: 12px"
          ></el-rate>
        </el-form-item>
        <el-form-item label="综合评语：" required="true">
          <el-input
            type="textarea"
            autosize
            style="width: 300px; height: 60px"
            v-model="contentForm.evaluate"
            placeholder="请输入评语"
          ></el-input>
        </el-form-item>
        <el-form-item label="评价时间：" required="true">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="contentForm.createTime"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contentVisitable = false">取 消</el-button>
        <el-button type="primary" @click="evaluate()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
  <el-pagination
      alian="center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="tableData.length"
      background="true"  
      id="change"
    >
    </el-pagination>
  </div>
</template>

<script>
import api from "@/api/userdoc";
import deptApi from "@/api/department";
import { mapGetters } from "vuex";
export default {
  name: "employee",
  computed: {
    ...mapGetters(["name"]),
  },
  data() {
    return {
      contentVisitable: false,
      contentForm: {
        workingAbility: 0,
        workingAttitude: 0,
        communication: 0,
        evaluate: "",
        createTime: "",
        name: "",
        deptId: "",
        evaluator: "",
        userId:""
      },
      list: [],
      deptList: [],
      defaultProps: {
        children: "childrens",
        label: "name",
      },
      //判断是否为hr或部门经理
      isHR: false,
      imageUrl: "",
      add: {
        name: "",
        parentName: "",
        parentId: "",
        date: "",
        manger: "",
        orderNum: "",
      },
      innerVisible: false,
      listLoading: true, //加载圈圈，数据得到后要取消
      multipleSelection: [],
      downloadLoading: false,
      filename: "员工信息表", //表格名称
      //员工信息表
      tableData: [],
      searchId: "",
      dialogTableVisible: false,
      dialogFormVisible: false,
      superEmployee: false,
      //新员工信息
      newEmployee: {
        deptId: "",
        deptName: "",
        education: "",
        entryDate: "",
        mobile: "",
        name: "",
        age: "",
        userType: "0",
        identityCard: "",
        gender: "1",
        username: "",
        password: "",
      },
      formLabelWidth: "150px",
      createSuccess: false,
      //当前页数
      currentPage: 1,
      //一页几条数据
      pageSize: 10,
      rules: {
        name: [
          { required: true, message: "请输入员工姓名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        age: [
          { required: true, message: "请输入员工年龄", trigger: "blur" },
          { type: "number", message: "年龄必须为数字值" },
        ],
        identityCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            min: 15,
            max: 18,
            message: "请如实填写18位号码",
            trigger: "blur",
          },
          {
            required: true,
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号码",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请如实填写11位手机号码",
            trigger: "blur",
          },
          {
            required: true,
            pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    //监听对象中的属性变化，用字符串做函数名
    "newEmployee.userType"(val) {
      if (val == 3 || val == 4) {
        this.isHR = true;
      } else {
        this.isHR = false;
      }
    },
  },
  methods: {
    //初始化评价
    initEvalute(data) {
      this.contentVisitable = true
      this.contentForm.name = data.name
      this.contentForm.evaluator=this.name
      this.contentForm.deptId=data.deptId
      this.contentForm.userId=data.userId
    },
    //评价contentForm
    evaluate(){
      this.contentForm.workingAttitude=this.contentForm.workingAttitude*20
      this.contentForm.workingAbility=this.contentForm.workingAbility*20
      this.contentForm.communication=this.contentForm.communication*20
       api.eveluate(this.contentForm).then(response=>{
          this.$notify({
          title: '成功',
          message: '已提交对'+this.contentForm.name+'的评价',
          type: 'success'
        });
      }).catch(err=>{
          this.$message.error('网络繁忙，请刷新后重试')
      })
      setTimeout(() => {
        this.contentVisitable=false
        this.$router.go(0)
      }, 300);
    },
     

    //上传员工照片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //节点选中状态
    handleNodeClick(data) {
      this.newEmployee.deptName = data.name;
      this.newEmployee.deptId = data.deptId;
    },
    //打开选择上级部门列表
    openParentDept() {
      this.innerVisible = true;
    },
    //获取部门列表
    getDeptList() {
      deptApi
        .getDeptList()
        .then((response) => {
          let list = response.list;
          let deps = [];
          let ds = [];
          for (let index = 0; index < list.length; index++) {
            list[index].childrens = [];
            deps.push(list[index]);
          }
          deps.sort(this.cmp);
          for (let index = 0; index < deps.length; index++) {
            const element = deps[index];
            for (let index2 = 0; index2 < deps.length; index2++) {
              const element = deps[index2];
              if (deps[index2].parentId == deps[index].deptId) {
                deps[index].childrens.push(deps[index2]);
              }
            }
            if (deps[index].childrens.length != 0) {
              ds.push(deps[index]);
            }
          }
          this.deptList.push(ds[0]);
          let s = JSON.stringify(this.deptList);
          console.log(this.deptList);
        })
        .catch((err) => {
          this.$message.error("网络异常。请检查设置");
        });
    },
    // 创建员工合同
    create() {
      console.log(this.newEmployee.entryDate);
      let date = new Date(Date.parse(this.newEmployee.entryDate));
      this.newEmployee.entryDate =
        date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
      api
        .save(this.newEmployee)
        .then((response) => {
          this.$notify({
            title: "成功",
            message: "成功添加一条合同",
            type: "success",
          });
          setTimeout(() => {
            this.dialogFormVisible = false;
            this.$router.go(0);
          }, 300);
        })
        .catch((err) => {
          this.$message.error("网络错误");
        });
    },
    //查找员工
    search() {
      let key = 0;
      let list2 = this.tableData;
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].name == this.searchId) {
          this.list.push(this.tableData[i]);
          key = 1;
        }
      }
      // eslint-disable-next-line eqeqeq
      if (key == 0) {
        this.tableData = list2;
        this.$alert("没有找到该员工", "查询错误", {
          confirmButtonText: "确定",
          callback: (action) => {
            this.searchId = "";
          },
        });
      } else {
        this.tableData = this.list;
      }
    },

    handleSelectionChange(val) {
      console.log(val);
      for (let index = 0; index < val.length; index++) {
        const element = val[index];
        this.multipleSelection.push(element);
      }
    },
    //离职
    deleteDoc() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要办理离职手续的员工",
          type: "warning",
        });
      } else if (this.multipleSelection.length > 1) {
      } else {
        this.$confirm(
          "是否为" + this.multipleSelection[0].name + "办理离职手续？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            api
              .delete(this.multipleSelection[0].userId)
              .then((response) => {
                this.$notify({
                  title: "成功",
                  message: "已成功办理一条离职手续",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.go(0);
                }, 300);
              })
              .catch((err) => {
                this.$message.error("网络繁忙，请刷新后重试");
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    //下载员工列表
    handleDownload() {
      if (this.multipleSelection.length) {
        this.downloadLoading = true;
        import("@/vendor/Export2Excel").then((excel) => {
          const tHeader = [
            "userId",
            "name",
            "gender",
            "age",
            "mobile",
            "deptName",
            "deptId",
            "education",
            "identityCard",
            "entryDate",
            "leaveDate",
            "userType",
            "createTime",
            "updateTime",
            "companyId",
          ];
          const filterVal = [
            "userId",
            "name",
            "gender",
            "age",
            "mobile",
            "deptName",
            "deptId",
            "education",
            "identityCard",
            "entryDate",
            "leaveDate",
            "userType",
            "createTime",
            "updateTime",
            "companyId",
          ];
          const list = this.multipleSelection;
          const data = this.formatJson(filterVal, list);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
          });
          this.$refs.multipleTable.clearSelection();
          this.downloadLoading = false;
        });
      } else {
        this.$message({
          message: "请选择要导出的员工信息",
          type: "warning",
        });
      }
    },
    //处理下载的表格
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    //获取员工列表
    getList() {
      api
        .getList()
        .then((response) => {
          console.log(response.list);
          this.tableData = response.list;
          console.log(that.tableData);
        })
        .catch((err) => console.log(err));
    },
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    //跳转至员工详细信息页
    showMsg(id) {
      console.log(id);
      this.$router.push({ path: "onself", query: { id: id } });
    },
    selectDept() {
      this.innerVisible = false;
    },
    //检查hr用户名是否存在
    checkUsername() {
      api.checkUsername(this.newEmployee.username).then((response) => {
        if (response.msg == false) {
          this.$message.error("用户名已存在，请更改");
        }
      });
    },
  },
  created() {
    this.getList();
    this.getDeptList();
    this.listLoading = false;
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#delete{
  right: 0px ;
  width: 30%;
}
#image {
  position: absolute;
  top: 100px;
  left: 470px;
}
#topbtns {
   height: 40px; 
   width: 500px;
   position: absolute;
   top: -50px;
   right: 40px;
}
#main{
  position: absolute;
  top: 140px;
  margin: auto;
  width: 100%;
}
#container{
  height: 120%;
}
#data{
  width: 100%;
}
#change{
  position: absolute;
  bottom: 20px; 
  right: 0;
}
</style>
